package com.jwell.panprovider.service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.jwell.panprovider.R;
import com.jwell.panprovider.application.App;
import com.jwell.panprovider.application.ConstValue;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载服务
 */
public class DownloadService extends Service {
    //定义notification实用的ID
    private static final int NO_3 = 0x3;
    private static final int DOWN_UPDATE = 0;
    private static final int DOWN_OVER = 1;

    private String path;
    private MHandler handler;

    /**
     * 初始化下载器
     **/
    private void initDownManager() {
        if (path == null) {
            return;
        }
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        //下载以及安装线程模拟
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    //开启连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //设置超时的时间，5000毫秒即5秒
                    conn.setConnectTimeout(5000);
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    //设置获取方式为GET
                    conn.setRequestMethod("GET");
                    conn.connect();
                    builder.setSmallIcon(R.mipmap.ic_launcher);
                    builder.setContentTitle("下载中");
                    builder.setContentText("正在下载");
                    final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.notify(NO_3, builder.build());
                    builder.setProgress(100, 0, false);
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        int length = conn.getContentLength();
                        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                        File file = new File(ConstValue.FILE_NAME);
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }
                        byte[] buf = new byte[1024];
                        int size;
                        int count = 0;
                        FileOutputStream fos = new FileOutputStream(ConstValue.FILE_NAME);
                        while ((size = bis.read(buf)) != -2) {
                            count += size;
                            builder.setProgress(100, (int) (((float) count / length) * 100), false);
                            manager.notify(NO_3, builder.build());
                            //下载进度提示
                            Log.i("TAG", "下载" + (int) (((float) count / length) * 100) + "%");
                            builder.setContentText("下载" + (int) (((float) count / length) * 100) + "%");
                            fos.write(buf, 0, size);
                        }
                        // 通知完成
                        //下载完成后更改标题以及提示信息
                        builder.setContentTitle("开始安装");
                        builder.setContentText("安装中...");
                        //设置进度为不确定，用于模拟安装
                        builder.setProgress(0, 0, true);
                        manager.notify(NO_3, builder.build());
                        manager.cancel(NO_3);//设置关闭通知栏
                        // 通知完成
                        handler.sendEmptyMessage(DOWN_OVER);
                        fos.close();
                        bis.close();
                        conn.disconnect();
                    } else {
                        Looper.prepare();
                        Toast.makeText(App.Companion.getInstance(), "下载失败，请到官网或者应用市场下载体验新版!", Toast.LENGTH_LONG).show();
                        Looper.loop();
                        stopSelf();

                    }
                } catch (Exception e) {
                    Looper.prepare();
                    Toast.makeText(App.Companion.getInstance(), "下载失败，请到官网或者应用市场下载体验新版!", Toast.LENGTH_LONG).show();
                    Looper.loop();
                    System.out.println("e=" + e.toString());
                    stopSelf();
                }
            }
        }
        ).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getExtras() != null) {
            path = intent.getExtras().getString("filePath");
            // 调用下载
            handler = new MHandler(this);
            initDownManager();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        stopSelf();
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    static class MHandler extends Handler {
        WeakReference<DownloadService> outerClass;

        MHandler(DownloadService context) {
            outerClass = new WeakReference<>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWN_UPDATE: //下载中，更新进度
                    break;
                case DOWN_OVER: //下载完成，安装apk
                    File apkfile = new File(ConstValue.FILE_NAME);
                    if (!apkfile.exists()) {
                        return;
                    }
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    outerClass.get().startActivity(i);
                    outerClass.get().stopSelf();
                    break;
                default:
                    break;
            }
        }
    }
}